// Package quantumapi 提供量子引擎的HTTP API接口
package quantumapi

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/analysis"
)

// APIServer API服务器
type APIServer struct {
	Engine        *quantumcore.FourDimensionalEngine
	Router        *gin.Engine
	Port          string
	TruthAnalyzer *analysis.TruthAnalyzer
}

// Request and Response structures

type EncodeRequest struct {
	Data string `json:"data" binding:"required"`
}

type EncodeResponse struct {
	Success    bool    `json:"success"`
	Coherence  float64 `json:"coherence"`
	NumQubits  int     `json:"num_qubits"`
	Message    string  `json:"message"`
}

type ProcessRequest struct {
	Data string `json:"data" binding:"required"`
}

type ProcessResponse struct {
	Success      bool    `json:"success"`
	OutputData   string  `json:"output_data"`
	Coherence    float64 `json:"coherence"`
	Entropy      float64 `json:"entropy"`
	Fitness      float64 `json:"fitness"`
	CurrentCycle string  `json:"current_cycle"`
	ProcessTime  string  `json:"process_time"`
	Message      string  `json:"message"`
}

type HealthResponse struct {
	Timestamp       string                 `json:"timestamp"`
	Status          string                 `json:"status"`
	OverallScore    float64                `json:"overall_score"`
	MicroHealth     map[string]interface{} `json:"micro_health"`
	MesoHealth      map[string]interface{} `json:"meso_health"`
	MacroHealth     map[string]interface{} `json:"macro_health"`
	ObjectiveHealth map[string]interface{} `json:"objective_health"`
	Warnings        []string               `json:"warnings"`
	Recommendations []string               `json:"recommendations"`
}

// NewAPIServer 创建新的API服务器
func NewAPIServer(engine *quantumcore.FourDimensionalEngine, port string) *APIServer {
	router := gin.Default()

	server := &APIServer{
		Engine:        engine,
		Router:        router,
		Port:          port,
		TruthAnalyzer: analysis.NewTruthAnalyzer(),
	}

	server.setupRoutes()

	return server
}

// setupRoutes 设置路由
func (s *APIServer) setupRoutes() {
	api := s.Router.Group("/api/quantum")
	{
		// 量子编码
		api.POST("/encode", s.handleEncode)

		// 综合处理（四维一体）
		api.POST("/process", s.handleProcess)

		// 健康检查
		api.GET("/health", s.handleHealth)

		// 引擎信息
		api.GET("/info", s.handleInfo)

		// 介观平衡报告
		api.GET("/balance", s.handleBalance)

		// 宏观演化报告
		api.GET("/evolution", s.handleEvolution)

		// 客观周期报告
		api.GET("/rhythm", s.handleRhythm)

		// 真实性分析（新增）
		api.POST("/analyze/truth", s.handleTruthAnalysis)
		api.POST("/analyze/compare", s.handleCompareStatements)

		// 关闭引擎
		api.POST("/shutdown", s.handleShutdown)
	}
}

// handleEncode 处理量子编码请求
func (s *APIServer) handleEncode(c *gin.Context) {
	var req EncodeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "请求参数错误: " + err.Error(),
		})
		return
	}

	// 编码数据
	state, err := s.Engine.Micro.EncodeMicroSequence([]byte(req.Data))
	if err != nil {
		c.JSON(http.StatusInternalServerError, EncodeResponse{
			Success: false,
			Message: "量子编码失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, EncodeResponse{
		Success:   true,
		Coherence: state.Coherence,
		NumQubits: state.NumQubits,
		Message:   "量子编码成功",
	})
}

// handleProcess 处理综合处理请求（四维一体）
func (s *APIServer) handleProcess(c *gin.Context) {
	var req ProcessRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "请求参数错误: " + err.Error(),
		})
		return
	}

	// 四维处理
	result, err := s.Engine.ProcessData([]byte(req.Data))
	if err != nil {
		c.JSON(http.StatusInternalServerError, ProcessResponse{
			Success: false,
			Message: "处理失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, ProcessResponse{
		Success:      result.Success,
		OutputData:   string(result.Data),
		Coherence:    result.Coherence,
		Entropy:      result.Entropy,
		Fitness:      result.Fitness,
		CurrentCycle: result.CurrentCycle,
		ProcessTime:  result.ProcessTime.String(),
		Message:      result.Message,
	})
}

// handleHealth 处理健康检查请求
func (s *APIServer) handleHealth(c *gin.Context) {
	report := s.Engine.CheckQuantumHealth()

	c.JSON(http.StatusOK, HealthResponse{
		Timestamp:       report.Timestamp.Format(time.RFC3339),
		Status:          string(report.Status),
		OverallScore:    report.OverallScore,
		MicroHealth:     report.MicroHealth,
		MesoHealth:      report.MesoHealth,
		MacroHealth:     report.MacroHealth,
		ObjectiveHealth: report.ObjectiveHealth,
		Warnings:        report.Warnings,
		Recommendations: report.Recommendations,
	})
}

// handleInfo 处理引擎信息请求
func (s *APIServer) handleInfo(c *gin.Context) {
	info := s.Engine.GetEngineInfo()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"info":    info,
	})
}

// handleBalance 处理介观平衡报告请求
func (s *APIServer) handleBalance(c *gin.Context) {
	report := s.Engine.Meso.GetBalanceReport()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"balance": report,
	})
}

// handleEvolution 处理宏观演化报告请求
func (s *APIServer) handleEvolution(c *gin.Context) {
	report := s.Engine.Macro.GetEvolutionReport()
	c.JSON(http.StatusOK, gin.H{
		"success":   true,
		"evolution": report,
	})
}

// handleRhythm 处理客观周期报告请求
func (s *APIServer) handleRhythm(c *gin.Context) {
	report := s.Engine.Objective.GetRhythmReport()
	schedule := s.Engine.Objective.GetWorkCycleSchedule()

	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"rhythm":   report,
		"schedule": schedule,
	})
}

// handleTruthAnalysis 处理真实性分析请求
func (s *APIServer) handleTruthAnalysis(c *gin.Context) {
	var req struct {
		Content   string `json:"content" binding:"required"`
		Speaker   string `json:"speaker"`
		Context   string `json:"context"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "请求参数错误: " + err.Error(),
		})
		return
	}

	stmt := &analysis.Statement{
		ID:        time.Now().Format("20060102150405"),
		Content:   req.Content,
		Timestamp: time.Now(),
		Speaker:   req.Speaker,
		Context:   req.Context,
	}

	result, err := s.TruthAnalyzer.AnalyzeStatement(stmt)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"error":   "分析失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success":              true,
		"truth_score":          result.TruthScore,
		"coherence_score":      result.CoherenceScore,
		"consistency_score":    result.ConsistencyScore,
		"entropy_level":        result.EntropyLevel,
		"deception_indicators": result.DeceptionIndicators,
		"confidence":           result.Confidence,
		"analysis":             result.Analysis,
	})
}

// handleCompareStatements 处理多陈述对比请求
func (s *APIServer) handleCompareStatements(c *gin.Context) {
	var req struct {
		Statements []struct {
			Content string `json:"content" binding:"required"`
			Speaker string `json:"speaker"`
		} `json:"statements" binding:"required,min=2"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "请求参数错误，需要至少2个陈述: " + err.Error(),
		})
		return
	}

	statements := make([]*analysis.Statement, 0)
	for i, s := range req.Statements {
		statements = append(statements, &analysis.Statement{
			ID:        time.Now().Format("20060102150405") + string(rune(i)),
			Content:   s.Content,
			Timestamp: time.Now(),
			Speaker:   s.Speaker,
		})
	}

	result := s.TruthAnalyzer.CompareStatements(statements)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"result":  result,
	})
}

// handleShutdown 处理关闭请求
func (s *APIServer) handleShutdown(c *gin.Context) {
	if err := s.Engine.Shutdown(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "引擎已安全关闭",
	})
}

// Start 启动API服务器
func (s *APIServer) Start() error {
	return s.Router.Run(":" + s.Port)
}
